package com.ruoyi.teaching.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.li.work.mapper.SysDeptMapper;
import com.ruoyi.li.work.mapper.SysUserMapper;
import com.ruoyi.li.work.mapper.SysUserRoleMapper;
import com.ruoyi.teaching.domain.*;
import com.ruoyi.teaching.domain.vo.*;
import com.ruoyi.teaching.mapper.PlatformCCourseMapper;
import com.ruoyi.teaching.mapper.PlatformEExamMapper;
import com.ruoyi.teaching.mapper.PlatformEScoreMapper;
import com.ruoyi.teaching.mapper.PlatformQQuestionMapper;
import com.ruoyi.teaching.service.PlatformEScoreService;
import com.ruoyi.teaching.utils.UniversalUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 王旭
 * @since 2024-06-15
 */
@Service
public class PlatformEScoreServiceImpl extends ServiceImpl<PlatformEScoreMapper, PlatformEScore> implements PlatformEScoreService {

    @Autowired
    private PlatformEScoreMapper platformEScoreMapper;

    @Autowired
    private PlatformQQuestionMapper platformQQuestionMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private PlatformEExamMapper platformEExamMapper;

    @Autowired
    private PlatformCCourseMapper platformCCourseMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    /**
     * 根据ID查询考试信息
     *
     * @param id 考试ID
     * @return 查询结果
     */
    @Override
    public AjaxResult selectPlatformEScoreById(Long id) {
        // 查询考试信息
        PlatformEScore platformEScore = platformEScoreMapper.selectById(id);
        if (platformEScore == null) {
            return new AjaxResult(HttpStatus.ERROR, "考试信息有误，请联系管理员");
        }

        // 拷贝属性到VO对象
        PlatformEScoreVO platformEScoreVO = new PlatformEScoreVO();
        BeanUtils.copyProperties(platformEScore, platformEScoreVO);
        setTaskAndCourse(platformEScore, platformEScoreVO); // 设置考试和课程相关信息

        // 解析并处理分数信息
        List<ScoreInfoInVO> scoreInfoInVOS = JSONArray.parseArray(platformEScore.getScoreInfo(), ScoreInfoInVO.class);
        List<ScoreInfoOutVO> scoreInfoOutVOS = UniversalUtil.parseAndProcessScoreInformation(scoreInfoInVOS, platformQQuestionMapper);
        platformEScoreVO.setScoreInfo(scoreInfoOutVOS);

        // 处理学生的个人信息
        Long studentId = platformEScore.getStudentId().longValue();
        Long deptId = platformEScore.getDeptId().longValue();
        SysUser user = sysUserMapper.selectUserById(studentId);
        SysDept sysDept = sysDeptMapper.selectDeptById(deptId);
        platformEScoreVO.setStudentName(user.getNickName());
        platformEScoreVO.setAvatar(user.getAvatar());
        platformEScoreVO.setDeptName(sysDept.getDeptName());

        // 获取当前时间
        Date nowDate = DateUtils.getNowDate();
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        // 设置考试的状态
        setExamStatus(platformEScoreVO, format, nowDate);

        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", platformEScoreVO);
    }

    /**
     * 教师查询自己创建的考试列表
     *
     * @param pageNum       页码
     * @param pageSize      每页大小
     * @param examName      考试名称
     * @param examCourse    课程ID
     * @param vettingStatus 审核状态
     * @param deptId        部门ID
     * @return AjaxResult 包含分页信息和考试列表
     */
    @Override
    public AjaxResult selectPlatformEScoreListTeacher(
            Integer pageNum, Integer pageSize, String examName, Integer examCourse,
            Integer vettingStatus, Integer deptId) {
        // 创建查询条件包装器
        QueryWrapper<PlatformEScore> queryWrapper = new QueryWrapper<>();

        // 获取当前教师ID
        int teacherId = SecurityUtils.getUserId().intValue();
        queryWrapper.eq("create_id", teacherId);

        // 添加查询条件（若有）
        if (StringUtils.isNotBlank(examName)) {
            queryWrapper.like("exam_name", examName);
        }
        if (vettingStatus != null) {
            queryWrapper.eq("vetting_status", vettingStatus);
        }
        if (deptId != null) {
            queryWrapper.eq("dept_id", deptId);
        }

        // 根据 id 字段倒序排序
        queryWrapper.orderByDesc("id");

        // 执行查询
        List<PlatformEScore> result = platformEScoreMapper.selectList(queryWrapper);

        // 根据课程条件过滤
        List<PlatformEScore> filteredCourses = filterCourses(result, examCourse);

        // 创建VO对象列表并设置相关属性
        List<PlatformEScoreVO> platformEScoreVOS = new ArrayList<>();
        if (!CollectionUtils.isEmpty(filteredCourses)) {
            platformEScoreVOS = filteredCourses.stream().map(record -> {
                PlatformEScoreVO platformEScoreVO = new PlatformEScoreVO();
                BeanUtils.copyProperties(record, platformEScoreVO);

                // 处理学生的个人信息
                SysUser user = sysUserMapper.selectUserById(record.getStudentId().longValue());
                SysDept sysDept = sysDeptMapper.selectDeptById(record.getDeptId().longValue());

                platformEScoreVO.setStudentName(user.getNickName());
                platformEScoreVO.setAvatar(user.getAvatar());
                platformEScoreVO.setDeptName(sysDept.getDeptName());

                return platformEScoreVO;
            }).collect(Collectors.toList());
        }

        // 进行分页处理
        Page<PlatformEScoreVO> platformEScoreVOPage = toPage(platformEScoreVOS, pageNum, pageSize);

        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", platformEScoreVOPage);
    }

    private Page<PlatformEScoreVO> toPage(List<PlatformEScoreVO> platformEScoreVOS, Integer pageNum, Integer pageSize) {
        int total = platformEScoreVOS.size();
        int start = Math.min((pageNum - 1) * pageSize, total);
        int end = Math.min(start + pageSize, total);

        // 获取当前页的数据
        List<PlatformEScoreVO> paginatedList = platformEScoreVOS.subList(start, end);

        // 设置分页信息
        Page<PlatformEScoreVO> platformEScoreVOPage = new Page<>(pageNum, pageSize);
        platformEScoreVOPage.setRecords(paginatedList);
        platformEScoreVOPage.setTotal(total);
        return platformEScoreVOPage;
    }

    /**
     * 根据课程ID过滤考试
     *
     * @param scores     原始考试列表
     * @param examCourse 课程ID
     * @return 过滤后的考试列表
     */
    private List<PlatformEScore> filterCourses(List<PlatformEScore> scores, Integer examCourse) {
        if (examCourse == null) {
            return scores;
        }

        // 获取指定课程的考试
        List<PlatformEExam> exams = platformEExamMapper.selectByCourseId(examCourse);
        if (CollectionUtils.isEmpty(exams)) {
            return Collections.emptyList();
        }

        // 获取考试ID集合
        Set<Integer> examIds = exams.stream().map(PlatformEExam::getId).collect(Collectors.toSet());

        // 筛选出符合条件的考试
        return scores.stream()
                .filter(score -> examIds.contains(score.getExamId()))
                .collect(Collectors.toList());
    }


    /**
     * 更新考试信息
     *
     * @param platformEScore 考试信息
     * @return 更新结果
     */
    @Override
    public AjaxResult updatePlatformEScore(PlatformEScore platformEScore) {
        // 判断是否提交超时
        Long userId = SecurityUtils.getUserId();
        Long[] roleIds = sysUserRoleMapper.selectRoleIdbyUserId(userId);
        if (roleIds[0] == 4) {    // 学生身份进行判断
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Integer examId = platformEScore.getExamId();
            PlatformEExam platformEExam = platformEExamMapper.selectById(examId);
            try {
                Date submitTime = format.parse(platformEScore.getEndTime());
                Date deadline = format.parse(platformEExam.getSubmitTime());
                // Date startTime = format.parse(platformEExam.getStartTime());
                // if (submitTime.before(startTime)) {
                //     return new AjaxResult(HttpStatus.ERROR, "考试未开始，无法提交");
                // }
                if (deadline.before(submitTime)) {
                    return new AjaxResult(HttpStatus.ERROR, "提交时间已过，无法提交");
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }


        // 获取修改人信息
        UniversalCreateUpdate update = UniversalUtil.getCreateUpdate(sysUserMapper);
        platformEScore.setUpdateId(update.getId());
        platformEScore.setUpdateTime(DateUtils.getNowDate());
        platformEScore.setUpdateBy(update.getName());


        // 更新考试信息
        int updateResult = platformEScoreMapper.updateById(platformEScore);
        if (updateResult > 0) {
            return new AjaxResult(HttpStatus.SUCCESS, "更新成功");
        } else {
            return new AjaxResult(HttpStatus.ERROR, "更新失败");
        }
    }

    /**
     * 根据ID批量删除考试信息
     *
     * @param ids 考试ID数组
     * @return 删除结果
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public AjaxResult deletePlatformEScoreByIds(Long[] ids) {
        // 批量删除考试信息
        int deleteCount = platformEScoreMapper.deleteBatchIds(Arrays.asList(ids));
        if (deleteCount == ids.length) {
            return new AjaxResult(HttpStatus.SUCCESS, "删除成功");
        } else {
            throw new RuntimeException("删除失败");
        }
    }


    @Override
    public AjaxResult selectPlatformEScoreListStudent(Integer pageNum, Integer pageSize, Integer courseId, Integer vettingStatusAndIsClose, String examName) {
        // 创建查询条件包装器
        QueryWrapper<PlatformEScore> queryWrapper = new QueryWrapper<>();

        // 获取当前学生ID
        int studentId = SecurityUtils.getUserId().intValue();
        queryWrapper.eq("student_id", studentId); // 添加学生ID条件

        // 如果提供了课程ID，查询该课程的相关考试并添加条件
        if (courseId != null && courseId != 0) {
            List<Integer> examIds = platformEExamMapper.selectList(new QueryWrapper<PlatformEExam>().eq("exam_course", courseId))
                    .stream().map(PlatformEExam::getId).collect(Collectors.toList());

            if (examIds.isEmpty()) {
                return new AjaxResult(HttpStatus.SUCCESS, "该课程暂无考试", new Page<>(pageNum, pageSize));
            } else {
                queryWrapper.in("exam_id", examIds); // 添加考试ID条件
            }
        }

        // 添加审批状态条件
        if (vettingStatusAndIsClose != null && vettingStatusAndIsClose == 1) {
            queryWrapper.eq("vetting_status", 0);
        }

        // 根据 id 字段倒序排序
        queryWrapper.orderByDesc("id");

        if (StringUtils.isNotBlank(examName)) {
            queryWrapper.like("exam_name", examName);
        }

        // 查询所有符合条件的数据
        List<PlatformEScore> allEScores = platformEScoreMapper.selectList(queryWrapper);

        // 创建VO对象列表并设置相关属性
        List<PlatformEScoreVO> platformEScoreVOS = allEScores.stream().map(platformEScore -> {
            PlatformEScoreVO platformEScoreVO = new PlatformEScoreVO();
            setTaskAndCourse(platformEScore, platformEScoreVO); // 设置考试和课程相关信息
            BeanUtils.copyProperties(platformEScore, platformEScoreVO); // 复制属性
            return platformEScoreVO;
        }).collect(Collectors.toList());

        // 获取当前时间
        Date nowDate = DateUtils.getNowDate();
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        // 设置每个考试的状态
        platformEScoreVOS.forEach(platformEScoreVO -> setExamStatus(platformEScoreVO, format, nowDate));

        // 根据审批与结束状态过滤考试
        List<PlatformEScoreVO> filteredPlatformEScoreVOS = filterExamList(platformEScoreVOS, vettingStatusAndIsClose);

        // 进行分页处理
        Page<PlatformEScoreVO> platformEScoreVOPage = toPage(filteredPlatformEScoreVOS, pageNum, pageSize);

        // 返回结果
        return new AjaxResult(HttpStatus.SUCCESS, "操作成功", platformEScoreVOPage);
    }

    /**
     * 设置考试和课程相关信息
     *
     * @param platformTScore   考试对象
     * @param platformTScoreVO 考试视图对象
     */
    private void setTaskAndCourse(PlatformEScore platformTScore, PlatformEScoreVO platformTScoreVO) {
        PlatformEExam platformEExam = platformEExamMapper.selectById(platformTScore.getExamId());
        platformTScoreVO.setSubmitTime(platformEExam.getSubmitTime());
        platformTScoreVO.setExamTime(platformEExam.getExamTime());

        PlatformCCourse platformCCourse = platformCCourseMapper.selectById(platformEExam.getExamCourse());
        platformTScoreVO.setCourseName(platformCCourse.getCourseName());
        platformTScoreVO.setCourseId(platformCCourse.getId());
        platformTScoreVO.setCourseImage(platformCCourse.getCourseImage());
    }

    /**
     * 设置考试状态
     *
     * @param platformEScoreVO 考试视图对象
     * @param format           日期格式
     * @param nowDate          当前日期
     */
    private void setExamStatus(PlatformEScoreVO platformEScoreVO, DateFormat format, Date nowDate) {
        try {
            PlatformEExam platformEExam = platformEExamMapper.selectById(platformEScoreVO.getExamId());
            String submitTime = platformEExam.getSubmitTime();
            // String startTime = platformEExam.getStartTime();
            Date submit = format.parse(submitTime);
            // Date start = format.parse(startTime);
            boolean before = nowDate.before(submit);
            // boolean isStart = submit.before(start);
            // Status 0进行中，1超过时间的已结束，2待审核，3审核完成的已结束，4未开始
            if (before) {
                platformEScoreVO.setStatus(0);
            } else {
                platformEScoreVO.setStatus(1);
            }
            // if (isStart){
            //     platformEScoreVO.setStatus(4);
            // }
            if (platformEScoreVO.getVettingStatus() == 0 && platformEScoreVO.getExamStatus() == 1) {
                platformEScoreVO.setStatus(2);
            }
            if (platformEScoreVO.getVettingStatus() == 1 && platformEScoreVO.getExamStatus() == 1) {
                platformEScoreVO.setStatus(3);
            }
        } catch (ParseException e) {
            log.error("日期解析失败: " + platformEScoreVO.getSubmitTime(), e);
        }
    }

    /**
     * 根据审批与结束状态过滤考试列表
     *
     * @param platformEScoreVOS       考试视图对象列表
     * @param vettingStatusAndIsClose 审批与结束状态
     */
    private List<PlatformEScoreVO> filterExamList(List<PlatformEScoreVO> platformEScoreVOS, Integer vettingStatusAndIsClose) {
        if (vettingStatusAndIsClose == null) {
            return platformEScoreVOS;
        }

        return platformEScoreVOS.stream().filter(platformEScoreVO -> {
            switch (vettingStatusAndIsClose) {
                case 1:
                    return platformEScoreVO.getStatus() == 2;
                case 2:
                    return platformEScoreVO.getStatus() == 0;
                case 3:
                    return platformEScoreVO.getStatus() == 1 || platformEScoreVO.getStatus() == 3;
                // case 4:
                //     return platformEScoreVO.getStatus() == 4;
                default:
                    return true;
            }
        }).collect(Collectors.toList());
    }

}
